/**
 * 功能描述
 */

define(function (require, exports, module) {
	var aw = require("ajaxwrapper")
	var Dialog = require("dialog");
	var store =require("store");
	var activeUser = store.get("user");
    module.exports = {
    	save:function(widget){
    		var data = widget.get("form").getData();
			var datas = widget.get("optiongrid").getData();
			var PlanView = {};
			PlanView.plan = data;
			PlanView.list = datas;
			
			if(!data.verNumber){
				Dialog.alert({content:"请输入版本号!"});
				return false;
			}
			if(!data.year){
				Dialog.alert({content:"请输入年份!"});
				return false;
			}
			if(!data.planTitle){
				Dialog.alert({content:"请输入计划名称!"});
				return false;
			}
			
			if(datas && datas.length == 0){
				Dialog.alert({content:"至少输入一条目的地!"});
				return false;
			}
			
			for(var i=0;i<datas.length;i++){
				if(typeof datas[i].destination == "array"){
					Dialog.alert({content:"目的地不能为空!"});
					return false;
				}
				if(!datas[i].destination && !datas[i].destination.pkDestination){
					Dialog.alert({content:"目的地不能为空!"});
					return false;
				}
				if(!datas[i].startDate){
					Dialog.alert({content:"目的地开始日期不能为空!"});
					return false;
				}
				if(!datas[i].endDate){
					Dialog.alert({content:"目的地结束日期不能为空!"});
					return false;
				}
				var limitmax = datas[i].limitmax;
				var limitmin = datas[i].limitmin;
				if(typeof limitmax == "object"){
					datas[i].limitmax = limitmax.key;
				}
				if(typeof limitmin == "object"){
					datas[i].limitmin = limitmin.key;
				}
				if(typeof datas[i].destination == "object"){
					datas[i].destination = datas[i].destination.pkDestination;
				}
			}

			if(datas.length>1){
				for(var i=0;i<datas.length;i++){
					for(var j=0;j<datas.length;j++){
						if(i!==j && datas[j].destination == datas[i].destination && datas[j].startDate == datas[i].startDate && datas[j].endDate == datas[i].endDate){
							Dialog.alert({content:"团信息有重复，请检查后重新输入!"});
							return false;
						}
					}
				}
			}
			PlanView.plan.editor = activeUser.name;
			aw.saveOrUpdate("api/plan/saveplan",aw.customParam(PlanView),function(data){
				widget.hide([".J-optiongrid",".J-form"]).show([".J-grid"]);
				widget.get("subnav").hide(["return","save"]).show(["add","add","select"]);
				widget.get("grid").refresh();
			});
    	}
    };
});
